//
//  SXPPublishViewModel.swift
//  weibo
//
//  Created by shixinPeng on 16/3/6.
//  Copyright © 2016年 shixinPeng. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD


class SXPPublishViewModel: NSObject {

    
    //发送微博
    func pushPublishWeibo(images:[UIImage]?, info: NSAttributedString,success: (() -> ())){
        
        SVProgressHUD.show()
        
        //把表情转换为文字表情
        //1.创建一个用于接收数据的字符串
        var publishStr = ""
        
        //2.把信息分解成正常文本和表情符号
        info.enumerateAttributesInRange(NSMakeRange(0, info.length), options: []) { (data:[String: AnyObject],rang: NSRange, _) -> Void in
            //printLog(data)
            
            //进行拆分
            if let attachment = data["NSAttachment"] as? SXPtextAttachment{
                //是图片
                //printLog(attachment.enotion!.png!)
                publishStr += attachment.enotion!.chs!
            }else{//是文字
                //printLog((info.string as NSString).substringWithRange(rang)    )
                let str = (info.string as NSString).substringWithRange(rang)
                publishStr += str
            }
        }
        
        //printLog(publishStr)
        
  
    
        let manger = AFHTTPSessionManager()
        
        guard let token = SXPuserViewModels.shareInstance.access_token else{
            return
        }
        
        let params = ["access_token":token,"status":publishStr]
        
        
        if images!.count > 0 {//发送的是带照片
            
            let url = "https://upload.api.weibo.com/2/statuses/upload.json"
            //图片信息
            let imageData = UIImageJPEGRepresentation(images!.first!, 0.7)
            
            SXPHTTPClient.shareInstance.upload(url, params: params, data: imageData!, success: { (restult) -> () in
                SVProgressHUD.showSuccessWithStatus("发布成功")
                success()
                }, failure: { (error) -> () in
                    SVProgressHUD.showErrorWithStatus("发布失败")
            })
            
        }else{
            let url = "https://api.weibo.com/2/statuses/update.json"
            SXPHTTPClient.shareInstance.request(.POST, URLString: url, params: params, success: { (JSON) -> () in
                   SVProgressHUD.showSuccessWithStatus("发布成功", maskType: SVProgressHUDMaskType.Gradient)
                  success()
                }, failure: { (error) -> () in
                    
                    SVProgressHUD.showErrorWithStatus("发布错误!请检查网络", maskType: SVProgressHUDMaskType.Gradient)
                    return
            })
            
        }

        
    }
}
